// index.js
import BleManager from './../../services/bleManager.js';

Page({
  data: {
    devices: [],
    connected: false,
    connectedDevice: '',
    sendData: 'Hello ESP32',
    receivedData: [],
    log: [],
    isScanning: false,
    sendProgress: 0
  },

  onLoad() {
    this.bleManager = new BleManager();
    this._setupBleEventListeners();
    this._addLog('页面加载完成');
  },

  onUnload() {
    if (this.bleManager) {
      this.bleManager.disconnect();
    }
    wx.closeBluetoothAdapter();
  },

  // 设置BLE事件监听
  _setupBleEventListeners() {
    // 数据接收回调
    this.bleManager.onDataReceived = (data) => {
      this._addReceivedData(data);
    };

    // 错误回调
    this.bleManager.onError((error) => {
      this._handleBleError(error);
    });

    this.bleManager.onDeviceFound = (data) => {
      this._onDeviceFound(data);
    };

  },

  // 初始化蓝牙
  async initBluetooth() {
    this._addLog('初始化蓝牙...');
    const result = await this.bleManager.initBluetooth();
    
    if (result.success) {
      this._addLog('✅ 蓝牙初始化成功');
      wx.showToast({ title: '蓝牙就绪', icon: 'success' });
    } else {
      wx.showModal({
        title: '蓝牙初始化失败',
        content: result.error.message,
        showCancel: false
      });
    }
  },
 // 设备发现回调
 _onDeviceFound(device) {
  const existingDevice = this.data.devices.find(d => d.deviceId === device.deviceId);
  if (!existingDevice) {
    this._addLog(`发现设备: ${device.name || '未知设备'}`);
    console.log(device)
    this.data.devices.push({
      name: device.name || '未知设备',
      deviceId: device.deviceId
    });
    this.setData({ devices: this.data.devices });
  }
  if (device.advertisData) {
    const data = new Uint8Array(device.advertisData);
    const parsedData = this._decodeUTF8Array(data);
    console.log("parsedData",parsedData)
  }
},
_decodeUTF8Array(uint8Array) {
  if (!(uint8Array instanceof Uint8Array)) {
    throw new Error('入参必须为 Uint8Array 类型');
  }

  var out = "";
  var i = 0;
  var len = uint8Array.length;
  var c, char2, char3;

  while (i < len) {
    c = uint8Array[i++];
    switch (c >> 4) {
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx (单字节字符: ASCII)
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx 10xx xxxx (两字节字符)
        if (i >= len) {
          throw new Error('非法的UTF-8序列：两字节字符不完整');
        }
        char2 = uint8Array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx 10xx xxxx 10xx xxxx (三字节字符，如大部分中文)
        if (i + 1 >= len) {
          throw new Error('非法的UTF-8序列：三字节字符不完整');
        }
        char2 = uint8Array[i++];
        char3 = uint8Array[i++];
        out += String.fromCharCode(
          ((c & 0x0F) << 12) |
          ((char2 & 0x3F) << 6) |
          ((char3 & 0x3F) << 0)
        );
        break;
      default:
        // 可能是4字节字符或其他，此处为简化处理可跳过或抛出错误
        // 对于微信小程序与ESP32通讯的中文场景，以上三种情况已基本覆盖
        break;
    }
  }
  return out;
},
  // 开始搜索设备
  async startScan() {
    this.setData({ isScanning: true });
    this._addLog('开始搜索设备...');
    
    const initResult = await this.bleManager.initBluetooth();
    if (!initResult.success) return;

    const result = await this.bleManager.startDiscovery();
    
    if (result.success) {
      this._addLog('设备搜索中...');
      
      // 10秒后自动停止搜索
      setTimeout(() => {
        this.stopScan();
      }, 10000);
    } else {
      this.setData({ isScanning: false });
    }
  },

  // 停止搜索
  async stopScan() {
    await this.bleManager.stopDiscovery();
    this.setData({ isScanning: false });
    this._addLog('停止设备搜索');
  },



  // 连接设备
  async connectDevice(e) {
    const device = e.currentTarget.dataset.device;
    this._addLog(`连接设备: ${device.name}`);
    
    wx.showLoading({ title: '连接中...', mask: true });
    
    const result = await this.bleManager.connectDevice(device.deviceId);
    
    wx.hideLoading();
    
    if (result.success) {
      this.setData({
        connected: true,
        connectedDevice: device.name
      });
      this._addLog('✅ 设备连接成功');
      wx.showToast({ title: '连接成功', icon: 'success' });
    } else {
      wx.showModal({
        title: '连接失败',
        content: result.error.message,
        showCancel: false
      });
    }
  },

  // 发送数据
  async sendData() {
    const { sendData } = this.data;
    if (!sendData.trim()) {
      wx.showToast({ title: '请输入数据', icon: 'none' });
      return;
    }

    this._addLog(`发送数据: ${sendData}`);
    
    const callback = {
      onProgress: (current, total) => {
        const progress = Math.round((current / total) * 100);
        this.setData({ sendProgress: progress });
      },
      onSuccess: (seq) => {
        this._addLog(`✅ 数据包${seq}发送成功`);
      }
    };

    const result = await this.bleManager.sendData(sendData, callback);
    
    this.setData({ sendProgress: 0 });
    
    if (!result.success) {
      wx.showToast({ title: '发送失败', icon: 'none' });
    }
  },

  // 发送测试长数据
  async sendLongData() {
    const longData = '这是一条很长的测试数据，用于测试蓝牙分包功能。'.repeat(10);
    this._addLog(`发送长数据，长度: ${longData.length}`);
    
    this.setData({
      sendData:longData
    })
    this.sendData();
  },

  // 断开连接
  async disconnect() {
    const result = await this.bleManager.disconnect();
    
    if (result.success) {
      this.setData({
        connected: false,
        connectedDevice: '',
        devices: []
      });
      this._addLog('设备已断开连接');
      wx.showToast({ title: '已断开', icon: 'success' });
    }
  },

  // 处理接收到的数据
  _addReceivedData(data) {
    const timestamp = new Date().toLocaleTimeString();
    const newData = {
      time: timestamp,
      content: data
    };
    
    this.data.receivedData.unshift(newData);
    if (this.data.receivedData.length > 50) {
      this.data.receivedData = this.data.receivedData.slice(0, 50);
    }
    
    this.setData({ receivedData: this.data.receivedData });
    this._addLog(`📨 收到数据: ${data}`);
  },

  // 处理蓝牙错误
  _handleBleError(error) {
    this._addLog(`❌ 错误: ${error.message}`);
    
    if (error.code === 'DISCONNECTED') {
      this.setData({ connected: false });
    }
    
    wx.showToast({
      title: error.message,
      icon: 'none',
      duration: 3000
    });
  },

  // 添加日志
  _addLog(message) {
    const timestamp = new Date().toLocaleTimeString();
    const logEntry = `[${timestamp}] ${message}`;
    
    this.data.log.unshift(logEntry);
    if (this.data.log.length > 100) {
      this.data.log = this.data.log.slice(0, 100);
    }
    
    this.setData({ log: this.data.log });
    console.log(logEntry);
  },

  // 清空日志
  clearLog() {
    this.setData({ log: [] });
  },

  // 清空接收数据
  clearReceivedData() {
    this.setData({ receivedData: [] });
  },

  // 输入框变化
  onInputChange(e) {
    this.setData({ sendData: e.detail.value });
  }
});